<script setup lang="ts">
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { ref } from 'vue'
import type { UserTable } from '@/types/user'
import { userAdd } from '@/api/user'
const props = defineProps<{
  dMap: Map<string, string>
  // 刷新
  refresh: () => void
}>()
// 关闭
const emit = defineEmits<{
  (event: 'cDlg'): void
}>()
const addForm = ref<UserTable>({
  username: '',
  password: '',
  nickname: ''
})
const formRules = ref<FormRules<UserTable>>({
  username: [
    {
      required: true,
      message: '请输入账号'
    },
    {
      min: 8,
      max: 25,
      message: '账号长度为 8 - 25'
    }
  ],
  nickname: [
    {
      required: true,
      message: '请输入用户名'
    },
    {
      min: 1,
      max: 20,
      message: '用户名长度为 8 - 25'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入账号密码'
    },
    {
      max: 25,
      min: 8,
      message: '密码的长度应该为8-25个字符',
      trigger: 'blur'
    }
  ]
})

// 表单dom
const elFormRef = ref<FormInstance>()
function add() {
  elFormRef.value?.validate((d) => {
    if (d) {
      userAdd(addForm.value)
        .then((d) => {
          ElMessage.success(d.msg)
          emit('cDlg')
          props.refresh()
        })
        .catch((d) => {
          ElMessage.error(d.msg)
        })
    }
  })
}
</script>

<template>
  <el-form ref="elFormRef" :model="addForm" :rules="formRules" label-width="100px">
    <el-form-item required :label="(dMap.get('username') || 'username') + '：'" prop="username">
      <el-input
        v-model="addForm.username"
        :placeholder="'请输入' + dMap.get('username') || 'username'"
      ></el-input>
    </el-form-item>
    <el-form-item required :label="(dMap.get('nickname') || 'nickname') + '：'" prop="nickname">
      <el-input
        v-model="addForm.nickname"
        :placeholder="'请输入' + dMap.get('nickname') || 'nickname'"
      ></el-input>
    </el-form-item>
    <el-form-item required :label="(dMap.get('password') || 'password') + '：'" prop="password">
      <el-input
        v-model="addForm.password"
        :placeholder="'请输入' + dMap.get('password') || 'password'"
      ></el-input>
    </el-form-item>
    <el-form-item :label="(dMap.get('email') || 'email') + '：'" prop="email">
      <el-input
        v-model="addForm.email"
        :placeholder="'请输入' + dMap.get('email') || 'email'"
      ></el-input>
    </el-form-item>
    <el-form-item :label="(dMap.get('phone') || 'phone') + '：'" prop="phone">
      <el-input
        v-model="addForm.phone"
        :placeholder="'请输入' + dMap.get('phone') || 'phone'"
      ></el-input>
    </el-form-item>
    <div class="buttons">
      <el-button type="primary" @click="emit('cDlg')">取消</el-button>
      <el-button type="success" @click="add">保存</el-button>
    </div>
  </el-form>
</template>
<style scoped lang="less">
.buttons {
  display: flex;
  margin-top: 30px;
  justify-content: flex-end;
}
</style>
